﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
using TienTeTuong.DTO;

namespace TienTeTuong.DAO
{
    public class AdminDAO
    {
        public bool isAdmin(AdminDTO admin)
        {

            MySqlConnection SqlConnection = null;
            MySqlCommand MysqlCmd = null;
            MySqlDataReader reader;
            bool result = false;

            try
            {

                SqlConnection = new MySqlConnection(Global.ConnectionString);
                if (SqlConnection.State == ConnectionState.Closed)
                    SqlConnection.Open();
                MysqlCmd = new MySql.Data.MySqlClient.MySqlCommand();
                MysqlCmd.Connection = SqlConnection;

                MysqlCmd.CommandText = "Select * from `Admin` where `Admin`.`Name` = '" + admin.Name.ToLower() + "' and `Admin`.`Password` = '" + admin.Password + "'";

                reader = MysqlCmd.ExecuteReader();
                if (reader.Read()) {
                    result = true;  
                }
                MysqlCmd.Dispose();
                SqlConnection.Close();
                SqlConnection.Dispose();
                return result;
            }
            catch
            {
                if (MysqlCmd != null)
                    MysqlCmd.Dispose();
                if (SqlConnection != null)
                {
                    SqlConnection.Close();
                    SqlConnection.Dispose();
                }
                return false;
            }
        }

        public bool changePassword(AdminDTO admin)
        {

            MySqlConnection SqlConnection = null;
            MySqlCommand MysqlCmd = null;
            int reader;

            try
            {

                SqlConnection = new MySqlConnection(Global.ConnectionString);
                if (SqlConnection.State == ConnectionState.Closed)
                    SqlConnection.Open();
                MysqlCmd = new MySql.Data.MySqlClient.MySqlCommand();
                MysqlCmd.Connection = SqlConnection;

                MysqlCmd.CommandText = @"Update `tientetuong`.`Admin` SET `Admin`.`Password` = '" + admin.Password + "' where `Admin`.`Name` = '" + admin.Name + "'";

                reader = MysqlCmd.ExecuteNonQuery();
                MysqlCmd.Dispose();
                SqlConnection.Close();
                SqlConnection.Dispose();
                return reader > 0;
            }
            catch
            {
                if (MysqlCmd != null)
                    MysqlCmd.Dispose();
                if (SqlConnection != null)
                {
                    SqlConnection.Close();
                    SqlConnection.Dispose();
                }
                return false;
            }
        }
    }
}